import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { Template } from './schemas/template.schema';
import { GetTemplateListDto } from './dto/get-template-list.dto';

@Injectable()
export class TemplatesService {
  constructor(
    @InjectModel(Template.name) private templateModel: Model<Template>,
  ) { }

  // 获取模板列表
  async getTemplateList(dto: GetTemplateListDto) {
    const { page = 1, limit = 10 } = dto;
    const skip = (page - 1) * limit;

    const [list, count] = await Promise.all([
      this.templateModel
        .find()
        .skip(skip)
        .limit(limit)
        .sort({ createdAt: -1 })
        .exec(),
      this.templateModel.countDocuments(),
    ]);

    const pageCount = Math.ceil(count / limit);

    return {
      message: '查询成功！',
      data: {
        page: {
          currentPage: page,
          pageCount,
          count,
          isEnd: page >= pageCount,
        },
        list,
      },
      status: 200,
    };
  }

  // 获取模板详情
  async getTemplateDetail(id: string) {
    const template = await this.templateModel.findOne({ID: id});
    if (!template) {
      throw new NotFoundException('模板不存在');
    }
    return {
      message: '查询成功！',
      data: template,
      status: 200,
    };
  }
} 